package com.example.votes.config;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.core.JdbcTemplate;

@Configuration
public class DataSourceConfig {

    /*** 1) 主库 votes，JPA 默认使用 ***/
    @Bean
    @Primary
    @ConfigurationProperties("spring.datasource")
    public DataSourceProperties votesDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "votesDataSource")
    @Primary
    public DataSource votesDataSource(
            @Qualifier("votesDataSourceProperties") DataSourceProperties props) {
        return props.initializeDataSourceBuilder().build();
    }

    /*** 2) 日志库 votes_logs，JdbcTemplate 专用 ***/
    @Bean
    @ConfigurationProperties("spring.datasource-logs")
    public DataSourceProperties logsDataSourceProperties() {
        return new DataSourceProperties();
    }

    @Bean(name = "logsDataSource")
    public DataSource logsDataSource(
            @Qualifier("logsDataSourceProperties") DataSourceProperties props) {
        return props.initializeDataSourceBuilder().build();
    }

    /*** 如果你还需要在代码里操作主库，也可以注入 votesJdbcTemplate ***/
    @Bean(name = "votesJdbcTemplate")
    public JdbcTemplate votesJdbcTemplate(
            @Qualifier("votesDataSource") DataSource ds) {
        return new JdbcTemplate(ds);
    }

    @Bean(name = "logsJdbcTemplate")
    public JdbcTemplate logsJdbcTemplate(
            @Qualifier("logsDataSource") DataSource ds) {
        return new JdbcTemplate(ds);
    }
}
